package com.gongzhiyun.springboot3test.service.impl;

import com.gongzhiyun.springboot3test.service.RedisService;
import com.gongzhiyun.springboot3test.utils.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class RedisServiceImpl implements RedisService {
    private final StringRedisTemplate template;

    @Override
    public Boolean has(String key){
        return template.hasKey(key);
    }

    @Override
    public <T> void save(String key, T value, long expire){
        String v= JsonUtils.stringify(value);
        template.opsForValue().set(key,v, expire,TimeUnit.SECONDS);
    }

    @Override
    public <T> T get(String key, Class<T> clazz){
        String v= template.opsForValue().get(key);
        if (v==null){
            return null;
        }
        return JsonUtils.parse(v,clazz);
    }

    @Override
    public void delete(String key){
        template.delete(key);
    }

}
